//
//  ZLGestureLockViewController.m
//  HuaRun2
//
//  Created by admin on 2017/11/8.
//  Copyright © 2017年 Sunny. All rights reserved.
//

#import "ZLGestureLockViewController.h"
#import "ZLGestureLockView.h"
#import "UIButton+ImageTitleSpacing.h"
#import "LoginViewController.h"
#import "TouchLockViewController.h"

@interface ZLGestureLockViewController ()<ZLGestureLockDelegate>

@property (nonatomic, copy) NSString *lastGesturePsw;
@property (nonatomic) ZLUnlockType unlockType;
@property (nonatomic, strong) ZLGestureLockView *gestureLockView;

//标题label
@property (nonatomic, strong) UILabel * titleLabel;
@property (nonatomic, strong) UILabel * statusLabel;
@property (nonatomic, strong) UILabel * subStatusLabel;

//账号登陆
@property (nonatomic, strong) UIButton * accountBtn;
//指纹登陆
@property (nonatomic, strong) UIButton * touchBtn;
//重新设置手势
@property (nonatomic, strong) UIButton * resetGestureBtn;
@end

@implementation ZLGestureLockViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewInit {
    
    // 九宫格 手势密码页面
    ZLGestureLockView *gestureLockView = [[ZLGestureLockView alloc]initWithFrame:CGRectMake(0, (self.view.frame.size.height - self.view.frame.size.width + 64)/2, self.view.frame.size.width, self.view.frame.size.width)];
    gestureLockView.delegate = self;
    [self.view addSubview:gestureLockView];
    self.gestureLockView = gestureLockView;
    
    self.gestureLockView.delegate = self;
    
    switch (_unlockType) {
        case ZLUnlockTypeCreatePsw:
        {
            //            self.otherAcountBtn.hidden = self.forgetPswBtn.hidden = self.nameLabel.hidden = self.headIcon.hidden = YES;
        }
            break;
        case ZLUnlockTypeValidatePsw:
        {
            //            self.otherAcountBtn.hidden = self.forgetPswBtn.hidden = self.nameLabel.hidden = self.headIcon.hidden = NO;
            
            //        "huanYingBack" = "欢迎回来";
            //        "inputPhotoPsd" = "请绘制图案密码";
            _titleLabel.text = NSLocalizedString(@"huanYingBack", nil);
            _statusLabel.text = NSLocalizedString(@"inputPhotoPsd", nil);
            _accountBtn.hidden = NO;
            _touchBtn.hidden = NO;
        }
            break;
        default:
            break;
    }
    
    [self.view addSubview:self.titleLabel];
    [self.view addSubview:self.statusLabel];
    [self.view addSubview:self.subStatusLabel];
    
    [self.view addSubview:self.accountBtn];
    [self.view addSubview:self.touchBtn];
    [self.view addSubview:self.resetGestureBtn];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = backItem;

}

- (void)layoutInit {
    weakself(ws);
    [self.statusLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(ws.view);
        make.bottom.mas_equalTo(ws.subStatusLabel.mas_top).offset(-kMargin10);
        make.size.mas_equalTo(CGSizeMake(kMainScreenWidth, 20));
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(ws.view);
        make.bottom.mas_equalTo(ws.statusLabel.mas_top).offset(-kMargin10);
        make.size.mas_equalTo(CGSizeMake(kMainScreenWidth, 20));
    }];
    
    [self.subStatusLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(ws.view);
        make.bottom.mas_equalTo(ws.gestureLockView.mas_top).offset(-kMargin10);
        make.size.mas_equalTo(CGSizeMake(kMainScreenWidth, 20));
    }];

    [self.accountBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(ws.view);
        make.top.mas_equalTo(ws.gestureLockView.mas_bottom).offset(kMargin10);
        make.size.mas_equalTo(CGSizeMake(kMainScreenWidth / 2, 60));
    }];

    [self.touchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(ws.view);
        make.size.top.mas_equalTo(ws.accountBtn);
    }];

    [self.resetGestureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(ws.view);
        make.size.mas_offset(CGSizeMake(kMainScreenWidth, 60));
        make.top.mas_equalTo(ws.accountBtn);
    }];

}

- (void)dataInit {
    [_accountBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleTop     imageTitleSpace:kMargin10];
    [_touchBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleTop     imageTitleSpace:kMargin10];
}

#pragma mark - inint

- (instancetype)initWithUnlockType:(ZLUnlockType)unlockType {
    if (self = [super init]) {
        _unlockType = unlockType;
    }
    return self;
}

#pragma mark - viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self viewInit];
}
#pragma mark - ZLgestureLockViewDelegate

- (void)gestureLockView:(ZLGestureLockView *)lockView drawRectFinished:(NSMutableString *)gesturePassword {
    
    switch (_unlockType) {
        case ZLUnlockTypeCreatePsw: // 创建手势密码
        {
            [self createGesturesPassword:gesturePassword];
        }
            break;
        case ZLUnlockTypeValidatePsw: // 校验手势密码
        {
            [self validateGesturesPassword:gesturePassword];
        }
            break;
        default:
            break;
    }
}
#pragma mark - 类方法

+ (void)deleteGesturesPassword {
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"GesturesPassword"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (void)addGesturesPassword:(NSString *)gesturesPassword {
    [[NSUserDefaults standardUserDefaults] setObject:gesturesPassword forKey:@"GesturesPassword"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (NSString *)gesturesPassword {
    return [[NSUserDefaults standardUserDefaults] objectForKey:@"GesturesPassword"];
}

#pragma mark - private
//  创建手势密码
- (void)createGesturesPassword:(NSMutableString *)gesturesPassword {
    
    if (self.lastGesturePsw.length == 0) {
        
        if (gesturesPassword.length < 4) {
//            "inputFourDot" = "至少连接四个点，请重新输入";
            self.statusLabel.text =NSLocalizedString(@"inputFourDot",nil);
            return;
        }
        
        self.lastGesturePsw = gesturesPassword;
        //        "confirmPhotoPsd" = "请确认您的图案密码";
        self.statusLabel.text =  NSLocalizedString(@"confirmPhotoPsd", nil);
        _resetGestureBtn.hidden = NO;
        return;
    }
    
    if ([self.lastGesturePsw isEqualToString:gesturesPassword]) { // 绘制成功
        
        NSLog(@"%@", gesturesPassword);
        weakself(ws);
//        [self.navigationController dismissViewControllerAnimated:YES completion:^{
            // 保存手势密码
            [ZLGestureLockViewController addGesturesPassword:gesturesPassword];
            ws.clickBlock? ws.clickBlock(@""): nil;
//        }];
        
    }else {
//        "differentWithLast" = "与上一次绘制不一致，请重新绘制";
        self.statusLabel.text = NSLocalizedString(@"differentWithLast",nil);
    }
}

// 验证手势密码
- (void)validateGesturesPassword:(NSMutableString *)gesturesPassword {
    
    static NSInteger errorCount = 3;
    weakself(ws);
    if ([gesturesPassword isEqualToString:[ZLGestureLockViewController gesturesPassword]]) {
        
        [self dismissViewControllerAnimated:YES completion:^{
            errorCount = 3;
            ws.clickBlock? ws.clickBlock(@""): nil;

        }];
    } else {
        
        if (errorCount - 1 == 0) { //isOverCount 你已经输错3次了！ 请1分钟后重试
            self.subStatusLabel.text = NSLocalizedString(@"isOverCount", nil);
            
            //"reLogin" = "请重新登录";
            //"gestureUnInvaild"= "手势密码已失效";
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"gestureUnInvaild", nil) message:NSLocalizedString(@"reLogin", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", nil) otherButtonTitles:NSLocalizedString(@"confirm", nil), nil];
            [alertView show];
            
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isOverCount"];
            
            errorCount = 3;
            return;
        }
        
//        NSLocalizedString(@"leftCount", nil)
//        "leftCount" = "密码错误，还可以再输入";
//        "ci" = "次";
        self.subStatusLabel.text = [NSString stringWithFormat:@"%@%ld%@",NSLocalizedString(@"leftCount", nil), --errorCount,NSLocalizedString(@"ci", nil)];
    }
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    // 重新登陆
    NSLog(@"重新登陆");
    if (buttonIndex == 1) {
        [self accountLoginMethod];
    }
}

#pragma mark - 按钮点击事件 Anction

// 点击账号登陆按钮
- (void)accountLoginMethod {
    
    BOOL isOverCount = [[NSUserDefaults standardUserDefaults] boolForKey:@"isOverCount"];

    LoginViewController *loginVC = [LoginViewController new];
    weakself(ws);
    loginVC.clickBlock = ^(id result) {
        if (isOverCount) {
            [ws pushGestureLockView];
        }else {
            [ws.navigationController dismissViewControllerAnimated:YES
                                                        completion:^{
                                                            
                                                        }];
        }
    };
    [self.navigationController pushViewController:loginVC animated:YES];
}


// 点击指纹登陆
- (void)touchLoginMethod {
    TouchLockViewController *loginVC = [TouchLockViewController new];
    weakself(ws);
    loginVC.clickBlock = ^(id result) {
        [ws.navigationController dismissViewControllerAnimated:YES
                                                    completion:^{
                                                        
                                                    }];
    };
    [self.navigationController pushViewController:loginVC animated:YES];
}

//去设置手势密码
- (void)pushGestureLockView {
    ZLGestureLockViewController *loginVC =  [[ZLGestureLockViewController alloc] initWithUnlockType:ZLUnlockTypeCreatePsw];
    
    weakself(ws);
    loginVC.clickBlock = ^(id result) {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isOverCount"];
        
        [ws.navigationController dismissViewControllerAnimated:YES
                                                    completion:^{
                                                        
                                                    }];
    };
    [self.navigationController pushViewController:loginVC animated:YES];
    
}
// 点击重新绘制按钮
- (void)resetGesturePasswordMethod{
    
    self.lastGesturePsw = nil;
    self.statusLabel.text = NSLocalizedString(@"setPhotoPsd", nil);
    self.resetGestureBtn.hidden = YES;
}

#pragma mark getter setter
//        "setPhotoPsd" = "请设置图案密码";
- (UILabel *)statusLabel {
    if (!_statusLabel) {
        self.statusLabel = [UILabel new];
        _statusLabel.textAlignment = NSTextAlignmentCenter;
        _statusLabel.font = kFontSize15;
        _statusLabel.textColor = [UIColor grayColor];
        _statusLabel.text = NSLocalizedString(@"setPhotoPsd", nil);
    }
    return _statusLabel;
}

//        "setPhotoPsd" = "请设置图案密码";
- (UILabel *)subStatusLabel {
    if (!_subStatusLabel) {
        self.subStatusLabel = [UILabel new];
        _subStatusLabel.textAlignment = NSTextAlignmentCenter;
        _subStatusLabel.font = kGeneralFontSize;
        _subStatusLabel.textColor = [UIColor grayColor];
//        _subStatusLabel.text = NSLocalizedString(@"setPhotoPsd", nil);
    }
    return _subStatusLabel;
}

//        "huanYingUse" = "欢迎使用CM系统";
- (UILabel *)titleLabel {
    if (!_titleLabel) {
        self.titleLabel = [UILabel new];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.font = [UIFont boldSystemFontOfSize:20];
        _titleLabel.textColor = [UIColor orangeColor];
        _titleLabel.text = NSLocalizedString(@"huanYingUse", nil);
    }
    return _titleLabel;
}

//"useAccount" = "使用账号密码登陆";
- (UIButton *)accountBtn {
    if (!_accountBtn) {        
        UIButton * btn = [UIButton new];
        [btn setImage:[UIImage imageNamed:@"账号-(1)"] forState:(UIControlStateNormal)];
        [btn setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
        [btn setTitle:NSLocalizedString(@"useAccount", nil) forState:UIControlStateNormal];
        [btn.titleLabel setFont:kGeneralFontSize];
        btn.hidden = YES;
        [btn addTarget:self action:@selector(accountLoginMethod)
      forControlEvents:(UIControlEventTouchUpInside)];
        self.accountBtn = btn;
    }
    return _accountBtn;
}

//"usePhoto" = "使用指纹登陆";
- (UIButton *)touchBtn {
    if (!_touchBtn) {
        UIButton * btn = [UIButton new];
        [btn setImage:[UIImage imageNamed:@"手势-点击"] forState:(UIControlStateNormal)];
        [btn setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
        [btn setTitle:NSLocalizedString(@"usePhoto", nil) forState:UIControlStateNormal];
        [btn.titleLabel setFont:kGeneralFontSize];
        btn.hidden = YES;
        [btn addTarget:self action:@selector(touchLoginMethod)
      forControlEvents:(UIControlEventTouchUpInside)];
        self.touchBtn = btn;
    }
    return _touchBtn;
}


//"resetGesture" = "重新设置手势";
- (UIButton *)resetGestureBtn {
    if (!_resetGestureBtn) {
        UIButton * btn = [UIButton new];
        [btn setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
        [btn setTitle:NSLocalizedString(@"resetGesture", nil) forState:UIControlStateNormal];
        [btn.titleLabel setFont:kGeneralFontSize];
        btn.hidden = YES;
        [btn addTarget:self action:@selector(resetGesturePasswordMethod)
      forControlEvents:(UIControlEventTouchUpInside)];
        self.resetGestureBtn = btn;
    }
    return _resetGestureBtn;
}

@end
